package com.epro.standard.frontend.tagext;

import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.epro.standard.StandardException;
import com.epro.standard.infrastructure.dataaccess.DBManage;
import com.epro.standard.infrastructure.serviceaccess.ServiceAccessViewer;
import com.epro.standard.infrastructure.serviceaccess.ServiceAccessViewerImpl;
import com.epro.standard.usermenu.UserAccountVO;

public class MasterTableTag extends TagSupport {
    private String sortBy = "";
    private String sortCol = "";
    private boolean asc = true;
    private int Page = 1;
    private int index = 0;
    private int indexSort = -1;
    //
    private String noDetail = "true";
    private String noEdit = "false";
    private String noExtra = "true"; // daho modified 14/09/2004
    private String hintID = "";
    //	private String bgColorOnChecked = "#99CCFF";
    private String downloadURL = "";
    private String deleteURL = "";
    private String editURL = "";
    private String editWindowWidth = "30";
    private String editWindowHeight = "20";
    private String detailURL = "";
    private String detailWindowWidth = "40";
    private String detailWindowHeight = "30";
    private String[] alignValue = null;
    private String[] maxDataLength = null;
    private int maxRecord = 11;
    private String[][] data = null;
    private String[] head = null;
    private String tableWidth = "";
    private String[] dataWidth = null;
    private String isSort = "true";
    private UserAccountVO userLogin;
    private String menuID = "";
    private String tagName = "masterTable";
    private String idFormForCannotDelete = "";
    private String readonly = "false";


    private boolean dependentOnUser = true;

    public void setDependentOnUser(boolean dependentOnUser) {
        this.dependentOnUser = dependentOnUser;
    }

    public void setReadonly(String readonly) {
        this.readonly = readonly;
    }

    public void setIsSort(String isSort) {
        this.isSort = isSort;
    }

    public void setDataWidth(String[] dataWidth) {
        this.dataWidth = dataWidth;
    }

    public void setMaxRecord(int maxRecord) {
        this.maxRecord = maxRecord;
    }

    public void setNoExtra(String noExtra) {
        this.noExtra = noExtra;
    }

    public void setNoDetail(String noDetail) {
        this.noDetail = noDetail;
    }

    public void setNoEdit(String noEdit) {
        this.noEdit = noEdit;
    }

    public void setEditURL(String editURL) {
        String str = "";

        java.util.StringTokenizer token = 
            new java.util.StringTokenizer(editURL, "?");

        if (token.countTokens() >= 1)
            str += editURL + "&";
        else
            str += editURL + "?";

        this.editURL = str;
        //System.out.println(" edit url : "+str);		
    }

    public void setEditWindowWidth(String editWindowWidth) {
        this.editWindowWidth = editWindowWidth;
    }

    public void setEditWindowHeight(String editWindowHeight) {
        this.editWindowHeight = editWindowHeight;
    }

    public void setDetailURL(String detailURL) {
        String str = "";

        java.util.StringTokenizer token = 
            new java.util.StringTokenizer(detailURL, "?");

        if (token.countTokens() >= 1)
            str += detailURL + "&";
        else
            str += detailURL + "?";

        this.detailURL = str;

    }

    public void setDetailWindowWidth(String detailWindowWidth) {
        this.detailWindowWidth = detailWindowWidth;
    }

    public void setDetailWindowHeight(String detailWindowHeight) {
        this.detailWindowHeight = detailWindowHeight;
    }

    public void setAlignValue(String[] alignValue) {
        this.alignValue = alignValue;
    }

    public void setMaxDataLength(String[] maxDataLength) {
        this.maxDataLength = maxDataLength;
    }

    public void setData(String[][] data) {
        this.data = data;
    }

    public void setHead(String[] head) {
        this.head = head;
    }

    public void setDownloadURL(String downloadURL) {
        String str = "";

        java.util.StringTokenizer token = 
            new java.util.StringTokenizer(downloadURL, "?");

        //		if (token.countTokens() >= 1)
        //			str += downloadURL+"&";
        //		else
        //			str += downloadURL+"?";

        //		this.downloadURL = str;
        this.downloadURL = downloadURL;

    }

    private String getDownloadURL() {
        String str = "";

        java.util.StringTokenizer token = 
            new java.util.StringTokenizer(downloadURL, "?");

        //                System.out.println(" downlodURL token: "+downloadURL+" >> "+token.countTokens() );

        if (token.countTokens() > 1)
            str += downloadURL + "&";
        else
            str += downloadURL + "?";
        //		System.out.println(" === "+downloadURL);
        return str;
    }

    public void setDeleteURL(String deleteURL) {
        String str = "";

        java.util.StringTokenizer token = 
            new java.util.StringTokenizer(deleteURL, "?");

        if (token.countTokens() >= 1)
            str += deleteURL + "&";
        else
            str += deleteURL + "?";

        this.deleteURL = str;
    }

    public void setTableWidth(String tableWidth) {
        this.tableWidth = tableWidth;
    }

    private String getDeleteURL() {
        String str = "";

        java.util.StringTokenizer token = 
            new java.util.StringTokenizer(deleteURL, "?");

        if (token.countTokens() > 1)
            str += deleteURL + "&index=";
        else
            str += deleteURL + "?index=";

        return str;
    }

    public int doStartTag() throws JspException {
        Connection con = null;
        javax.servlet.http.HttpServletRequest request = 
            (javax.servlet.http.HttpServletRequest)pageContext.getRequest();
        javax.servlet.http.HttpSession session = request.getSession(true);
        if (session.getAttribute("userLogin") != null && dependentOnUser) {
            userLogin = (UserAccountVO)session.getAttribute("userLogin");
            if (session.getAttribute("fileInfoUtil") != null)
                menuID = 
                        ((com.epro.standard.frontend.util.FileInfoUtil)session.getAttribute("fileInfoUtil")).getMenuIDCode();
            else if (session.getAttribute("fileInfoUtil") != null)
                menuID = (String)session.getAttribute("sessionMenuIDCode");
        }

        init();
        try {
            /* add line for bug with OC4J 9.x , fix always remember as viewtable if there're change value to viewtable once */
            tagName = "masterTable";


            //			javax.servlet.http.HttpServletRequest request = pageContext.getRequest();
            con = new DBManage().getConnection();

            deleteURL = "action=\"" + getDeleteURL() + index + "\"";
            downloadURL = getDownloadURL(); //daho modified 14/09/2004

            ServiceAccessViewer service;


            if (readonly.equals("true")) {
                tagName = "viewtable";
                deleteURL = "";
                idFormForCannotDelete = " idForm=\"master1\" ";

                if (!(userLogin == null || menuID == null || 
                      menuID.equals(""))) {
                    service = 
                            new ServiceAccessViewerImpl(userLogin.getUA_USER_ID(), 
                                                        menuID, 
                                                        userLogin.getUA_ROLE_ID(), 
                                                        userLogin.getUA_USER_GROUP_ID(), 
                                                        con);
                    if (!service.canUpdate())
                        noEdit = "true";
                }
            } else {
                if (!(userLogin == null || menuID == null || 
                      menuID.equals(""))) {
                    service = 
                            new ServiceAccessViewerImpl(userLogin.getUA_USER_ID(), 
                                                        menuID, 
                                                        userLogin.getUA_ROLE_ID(), 
                                                        userLogin.getUA_USER_GROUP_ID(), 
                                                        con);
                    if (!service.canUpdate())
                        noEdit = "true";

                    if (!service.canDelete()) {
                        tagName = "viewtable";
                        deleteURL = "";
                        idFormForCannotDelete = " idForm=\"master1\" ";

                    }

                }
            }
            String str = "";

            JspWriter out = pageContext.getOut();

            str += 
"<FORM name=\"master1\" method=\"POST\"" + deleteURL + " >\n";

            str += getHeadSort();
            str += getBlockData();

            //System.out.println(!service.canDelete());
            out.println(str);
        } catch (StandardException ioe) {
            ioe.printStackTrace();
        } catch (java.io.IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (SQLException e) {
                System.out.println("SQL Exception");
                e.printStackTrace();
            }
        }

        return EVAL_BODY_INCLUDE;
    }

    public int doEndTag() throws JspException {
        init();
        try {
            String str = "";
            JspWriter out = pageContext.getOut();
            javax.servlet.http.HttpServletRequest request = 
                (javax.servlet.http.HttpServletRequest)pageContext.getRequest();

            if (!tagName.equals("viewtable"))
                str += 
"<INPUT TYPE=\"hidden\" name =\"redirectPage\" value=\"" + 
 request.getRequestURI() + "\">";
            str += "</FORM>";

            out.println(str);
        } catch (java.io.IOException ioe) {
            ioe.printStackTrace();
        }

        return EVAL_PAGE;
    }

    private void init() {
        javax.servlet.http.HttpServletRequest request = 
            (javax.servlet.http.HttpServletRequest)pageContext.getRequest();

        String sortBy = request.getParameter("sortBy");
        String sortCol = head[0];

        if (sortBy != null) {
            for (int i = 0; i < head.length; i++) {
                if (Integer.parseInt(sortBy) == i) {
                    sortCol = head[i];
                    indexSort = i;
                    break;
                }
            }
        }
        boolean asc = true;
        if (request.getParameter("isAsc") != null) {
            asc = 
Boolean.valueOf(request.getParameter("isAsc")).booleanValue();
        }
        //********************** calculate number of page ************************
        if (request.getParameter("page") != null)
            Page = Integer.parseInt(request.getParameter("page"));
        else
            Page = 1;

        // *****************************************************************************

        // ********************** calculate  index of record ************************
        //		if (request.getParameter("page") != null)
        //		{
        index = (this.Page - 1) * maxRecord;
        //		}
        // *****************************************************************************

        this.sortBy = sortBy;
        this.sortCol = sortCol;
        this.asc = asc;
    }

    private String getHeadSort() {
        String str = "";

        str += "<epro:" + tagName + " ";
        if (hintID.equals(""))
            hintID = "hint1";
        str += " hintID=\"" + hintID + "\"";

        str += " currentSort='" + sortBy + "'";
        str += idFormForCannotDelete;
        if (!(tableWidth.equals("")))
            str += " tableWidth=\"" + tableWidth + "\"";

        str += 
" noExtra='" + noExtra.toLowerCase() + "' "; // daho modified 14/09/2004

        str += " noDetail='" + noDetail.toLowerCase() + "' ";
        str += " noEdit='" + noEdit.toLowerCase() + "' ";
        if (this.isSort != null)
            str += " isSort=\"" + isSort + "\"";
        str += ">\n";
        for (int i = 0; i < head.length; i++) {
            str += "   <blockSort label='" + head[i] + "'";
            str += 
((sortBy != null) && (Integer.parseInt(sortBy) == i)) ? " sort=\"true\" " : 
" sort=\"false\"";
            if (i == indexSort)
                str += " asc='" + asc + "'";
            if (dataWidth != null)
                str += " width=\"" + dataWidth[i] + "\"";
            str += " />\n";
        }
        str += "</epro:" + tagName + ">\n";
        return str;
    }

    private String getBlockData() {
        String str = "";

        for (int i = index; i < (index + maxRecord); i++) {
            if (i >= data[0].length) {
                str += "<epro:" + tagName + " ";

                if (hintID.equals(""))
                    hintID = "hint1";
                str += " hintID=\"" + hintID + "\"";

                if (!(tableWidth.equals("")))
                    str += " tableWidth=\"" + tableWidth + "\"";
                str += ">\n";
                for (int j = 0; j < head.length; j++)
                    str += "   <blockEmpty/>\n";
                str += "</epro:" + tagName + ">\n";
            } else {
                str += 
"<epro:" + tagName + " rowID='" + (i - index) + "'" + idFormForCannotDelete + 
 " editURL=\"" + editURL + "index=" + i + "\" editWindowWidth='" + 
 editWindowWidth + "' editWindowHeight='" + editWindowHeight + "' ";

                if (hintID.equals(""))
                    hintID = "hint1";
                str += " hintID=\"" + hintID + "\"";

                if (noDetail.toLowerCase().equals("false"))
                    str += 
" detailURL=\"" + detailURL + "index=" + i + "\" detailWindowWidth='" + 
 detailWindowWidth + "' detailWindowHeight='" + detailWindowHeight + "' ";
                str += " noDetail='" + noDetail.toLowerCase() + "' ";
                str += " noEdit='" + noEdit.toLowerCase() + "' ";

                str += 
" downloadURL=\"" + downloadURL + "index=" + i + "&action=download\" "; // dho modified 14/09/2004                                
                str += 
" noExtra='" + noExtra.toLowerCase() + "' "; // dho modified 14/09/2004

                if (!(tableWidth.equals("")))
                    str += " tableWidth=\"" + tableWidth + "\"";

                String extraAlt = "";
                String updateAlt = "";
                String detailAlt = "";
                try {
                    updateAlt = 
                            com.epro.standard.frontend.util.StringUtil.encode2Thai(com.epro.standard.frontend.datasetup.MessageManager.getString("toolbarUpdate"));
                    detailAlt = 
                            com.epro.standard.frontend.util.StringUtil.encode2Thai(com.epro.standard.frontend.datasetup.MessageManager.getString("toolbarDetail"));
                    extraAlt = 
                            com.epro.standard.frontend.util.StringUtil.encode2Thai(com.epro.standard.frontend.datasetup.MessageManager.getString("toolbarExtra"));
                } catch (java.io.IOException e) {
                    e.printStackTrace();
                }
                str += 
" extraAlt=\"" + extraAlt + "\""; //daho modified 14/09/2004
                str += " updateAlt=\"" + updateAlt + "\"";
                str += " detailAlt=\"" + detailAlt + "\"";
                str += ">\n";

                for (int j = 0; j < head.length; j++) {
                    str += "<blockData label=\"" + data[j][i] + "\" ";
                    if (!(alignValue[j].equals("")))
                        str += " alignValue='" + alignValue[j] + "' ";
                    if (!(maxDataLength[j].equals("0")))
                        str += "maxLength='" + maxDataLength[j] + "' ";
                    if (dataWidth != null)
                        str += " width=\"" + dataWidth[j] + "\"";
                    str += "/>\n";
                }
                str += "</epro:" + tagName + ">\n";
            }
        }
        return str;
    }

    /**
     * Gets the hintID
     * @return Returns a String
     */
    public String getHintID() {
        return hintID;
    }

    /**
     * Sets the hint
     * @param hint The hint to set
     */
    public void setHintID(String hintID) {
        this.hintID = hintID;
    }


    /**
     * Gets the userLogin
     * @return Returns a UserAccountVO
     */
    public UserAccountVO getUserLogin() {
        return userLogin;
    }

    /**
     * Sets the userLogin
     * @param userLogin The userLogin to set
     */
    public void setUserLogin(UserAccountVO userLogin) {
        this.userLogin = userLogin;
    }


    /**
     * Gets the menuID
     * @return Returns a String
     */
    public String getMenuID() {
        return menuID;
    }

    /**
     * Sets the menuID
     * @param menuID The menuID to set
     */
    public void setMenuID(String menuID) {
        this.menuID = menuID;
    }


}

